<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/freedom.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/freedom.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">


  <link rel="manifest" href="/images/manifest.json">


  <meta name="msapplication-config" content="/images/browserconfig.xml">



  <meta name="keywords" content="MySQL必知必会学习-复习,">










<meta name="description" content="创建和操纵表创建表MySQL不仅用于表数据操纵，而且还可以用来执行数据库和表的所有操作，包括表本身的创建和处理。 创建表可直接使用SQl可视化工具(例如 Navicat，SQLyog等)创建(实际还是帮你生成创建的SQL语句，毕竟SQL服务器只认识SQL语句)，也可以使用SQL语句–CREATE TABLE创建(个人推荐！)。 使用CREATE TABEL创建一个表，需要以下信息: 新表的名字，">
<meta name="keywords" content="MySQL必知必会学习-复习">
<meta property="og:type" content="article">
<meta property="og:title" content="MySQL操作表-table">
<meta property="og:url" content="http://xuren.tech/2019/07/23/MySQL操作表-table/index.html">
<meta property="og:site_name" content="Xuren&#39;s Blogs">
<meta property="og:description" content="创建和操纵表创建表MySQL不仅用于表数据操纵，而且还可以用来执行数据库和表的所有操作，包括表本身的创建和处理。 创建表可直接使用SQl可视化工具(例如 Navicat，SQLyog等)创建(实际还是帮你生成创建的SQL语句，毕竟SQL服务器只认识SQL语句)，也可以使用SQL语句–CREATE TABLE创建(个人推荐！)。 使用CREATE TABEL创建一个表，需要以下信息: 新表的名字，">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-08-14T04:44:16.891Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MySQL操作表-table">
<meta name="twitter:description" content="创建和操纵表创建表MySQL不仅用于表数据操纵，而且还可以用来执行数据库和表的所有操作，包括表本身的创建和处理。 创建表可直接使用SQl可视化工具(例如 Navicat，SQLyog等)创建(实际还是帮你生成创建的SQL语句，毕竟SQL服务器只认识SQL语句)，也可以使用SQL语句–CREATE TABLE创建(个人推荐！)。 使用CREATE TABEL创建一个表，需要以下信息: 新表的名字，">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://xuren.tech/2019/07/23/MySQL操作表-table/">



  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/099563b3.js","daovoice")
  daovoice('init', {
      app_id: "099563b3"
    });
  daovoice('update');
  </script>





  <title>MySQL操作表-table | Xuren's Blogs</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Xuren's Blogs</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://xuren.tech/2019/07/23/MySQL操作表-table/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Xuren">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/freedom.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Xuren's Blogs">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">MySQL操作表-table</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-07-23T10:25:07+08:00">
                2019-07-23
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/MySQL/" itemprop="url" rel="index">
                    <span itemprop="name">MySQL</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.1k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  7
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="创建和操纵表"><a href="#创建和操纵表" class="headerlink" title="创建和操纵表"></a>创建和操纵表</h1><h2 id="创建表"><a href="#创建表" class="headerlink" title="创建表"></a>创建表</h2><p>MySQL不仅用于表数据操纵，而且还可以用来执行数据库和表的所有操作，包括表本身的创建和处理。</p>
<p>创建表可直接使用SQl可视化工具(例如 Navicat，SQLyog等)创建(实际还是帮你生成创建的SQL语句，毕竟SQL服务器只认识SQL语句)，也可以使用SQL语句–CREATE TABLE创建(个人推荐！)。</p>
<p>使用CREATE TABEL创建一个表，需要以下信息:<br> <strong>新表的名字</strong>，在关键字CREATE TABLE之后给出；<br> <strong>表列的名字和定义，用逗号分隔</strong>。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">#示例语句</span><br><span class="line">CREATE TABLE table_name </span><br><span class="line">(column1(列名) int(指定数据类型) NOT NULL  AUTO_INCREMENT(一些该列的限定规则),</span><br><span class="line">column2 char NOT NULL(一些该列的限定规则),........, </span><br><span class="line">PRIMARY KEY(column1,...... )(指定主键等))</span><br><span class="line">ENGINE=InnoDB  CHARSET=utf8;</span><br><span class="line">#ENGINE=InnoDB  设置表的引擎(MySQL默认为InnoDB) 还可设置 字符集等</span><br><span class="line"># MySQL支持的数据类型 参见 MySQL数据类型</span><br><span class="line"># 创建表时，格式尽量清晰(如上所示，一行一行分明)，便于阅读与理解</span><br></pre></td></tr></table></figure>

<p>如果你仅想<strong>在一个表不存在时创建它</strong>，应该在表名后给出IF NOT EXISTS。它只是查看表名是否存在，并且仅在表名不存在时创建它.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">CREATE TABLE table_name IF NOT EXIST (.............);</span><br></pre></td></tr></table></figure>

<p><strong>使用NULL值:</strong>在创建表时 如果<strong>指定列为NOT NULL</strong>,则<strong>在插入数据时，该列一定要有具体值，否则会报错</strong>，且插入失败！  （没有NOT NULL的列则随意，没指定时默认为 NULL)</p>
<p><strong>理解NULL</strong>: 不要把NULL值与空串相混淆。NULL值是没有值，它不是空串。如果指定’’（两个单引号，其间没有字符），这在NOT NULL列中是允许的。空串是一个有效的值，它不是无值。NULL值用关键字NULL而不是空串指定。 即 <strong>只有 NULL才是真NULL</strong>，其他任意  均为非NULL。</p>
<h3 id="主键再介绍"><a href="#主键再介绍" class="headerlink" title="主键再介绍"></a>主键再介绍</h3><p><strong>主键值必须唯一！</strong> </p>
<p>表中的每个行必须具有唯一的主键值。如果<strong>主键使用单个列，则它的值必须唯一</strong>。如果<strong>使用多个列，则这些列的组合值必须唯一</strong>。迄今为止我们看到的CREATE TABLE例子都是用单个列作为主键。</p>
<p><strong>使用单列:</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">方式1: PRIMARY KEY(column_name)</span><br><span class="line">方式2: column_name  type  PRIMARY KEY</span><br></pre></td></tr></table></figure>

<p><strong>使用多列:</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">PRIMARY KEY(column1,column2,........) #放在建表语句的括号内语句最后处即可</span><br></pre></td></tr></table></figure>

<p>主键和NULL值:，主键为其值唯一标识表中每个行的列。<strong>主键中只能使用不允许NULL值的列</strong>。允许NULL值的列不能作为唯一标识.</p>
<h3 id="AUTO-INCREMENT"><a href="#AUTO-INCREMENT" class="headerlink" title="AUTO_INCREMENT"></a>AUTO_INCREMENT</h3><p>最简单也是最高效的<strong>自增</strong>。</p>
<p>每个表<strong>只允许一个AUTO_INCREMENT列</strong>，而且它<strong>必须被索引</strong>（如，通过使它成为主键）。</p>
<p><strong>覆盖AUTO_INCREMENT</strong>：你可以简单地在INSERT语句中指定一个值，只要它是唯一的（至今尚未使用过）即可，该值将被用来替代自动生成的值。后续的增量将从你手动指定的值开始。</p>
<p><strong>确定AUTO_INCREMENT值</strong>：在使用AUTO_INCREMENT时，你也可以使用<strong>函数last_insert_id()</strong> 来获取你所插入记录的 自增值！此语句返回最后一个AUTO_INCREMENT值，然后可以将它用于后续的MySQL语句。</p>
<p>猜想:<strong>MyBatis的 返回自增键</strong>[useGeneratedKeys=*”true”* keyProperty=*”id”<em>]*</em>可能**也是这个原理.</p>
<h3 id="指定列的默认值"><a href="#指定列的默认值" class="headerlink" title="指定列的默认值"></a>指定列的默认值</h3><p>如果在插入行时没有给出值，MySQL允许指定此时使用的默认值。默认值用CREATE TABLE语句的列定义中的DEFAULT关键字指定。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">colum1 int NOT NULL DEFAULT 1,</span><br><span class="line"># 如上所示， 该int型数据如果没有指定值， 则其默认值为1</span><br><span class="line"># DEFAULT 与 NOT NULL完全独立哦，两者并不是一定要同时出现。上面只是个例子而已</span><br></pre></td></tr></table></figure>

<p>MySQL<strong>只支持</strong> <strong>常量作为默认值</strong>，不允许函数为默认值。</p>
<p><strong>使用默认值而不是NULL值</strong>: 许多数据库开发人员使用默认值而不是NULL列，特别是对用于计算或数据分组的列更是如此。</p>
<h3 id="引擎类型"><a href="#引擎类型" class="headerlink" title="引擎类型"></a>引擎类型</h3><p>MySQL有一个具体管理和处理数据的内部引擎。</p>
<p>在创建语句最后的  ENGINE=InnoDB 即为指定该表的内部引擎为InnoDB。</p>
<p>MySQL与其他DBMS不一样，它具有多种引擎。它打包多个引擎，这些引擎都隐藏在MySQL服务器内，全都能执行CREATE TABLE和SELECT等命令。为什么要发行多种引擎呢？因为它们<strong>具有各自不同的功能和特性</strong>，为<strong>不同的任务选择正确的引擎</strong>能获得良好的功能和灵活性。</p>
<p>几个需要了解知道的引擎：<br> <strong>InnoDB</strong>是一个可靠的事务处理引擎（参见第26章），它<strong>不支持全文</strong><br><strong>本搜索</strong>；
 <strong>MEMORY</strong>在功能等同于MyISAM，但由于<strong>数据存储在内存</strong>（不是磁盘）<br>中，<strong>速度很快（特别适合于临时表）</strong>；
 <strong>MyISAM</strong>是一个性能极高的引擎，它<strong>支持全文本搜索</strong>（参见第18章），<br>但<strong>不支持事务</strong>处理。</p>
<p>(InnoDB与MyISAM以及其他引擎当然还有其他不同差别，此处不再赘述)具体可查看<a href="https://dev.mysql.com/doc/refman/8.0/en/show-engines.html" target="_blank" rel="noopener">对应官方文档</a>。</p>
<p><strong>引擎混用</strong>:同一个数据库里不同的表了可以使用不同的引擎以满足各自的需要。</p>
<p><strong>外键不能跨引擎</strong>:混用引擎类型有一个大缺陷。外键（用于强制实施引用完整性）不能跨引擎，即使用一个引擎的表不能引用具有使用不同引擎的表的外键。</p>
<p>就本人目前的短浅见识而言， InnoDB似乎是用的最多的(毕竟大多数业务是需要用到事务的)。你应该选以需求来为你的数据表选择最合适的引擎。在计算机领域，没有绝对完美的技术，只有最符合业务需求的技术。 人生也大概是这样吧，</p>
<h2 id="更新表"><a href="#更新表" class="headerlink" title="更新表"></a>更新表</h2><p>ALTER TABLE语句: 更新表定义。</p>
<p>理想状态下，当<strong>表中存储数据以后</strong>，该<strong>表就不应该再被更新</strong>。在表的设计过程中需要花费大量时间来考虑，以便后期不对该表进行大的改动。(所以设计数据库也是个很重要的东西 )</p>
<p>使用ALTER TABLE，需要一下信息:<br> 在ALTER TABLE之后给出要更改的表名（该表必须存在，否则将<br>出错）；<br> 需要更改的列。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE table_name ADD column_name type other;</span><br><span class="line">#顾名思义， 该命令给表 增添一列column</span><br><span class="line">ALTER TABLE table_name DROP COLUMN  column_name;</span><br><span class="line">#删除表中的列</span><br></pre></td></tr></table></figure>

<p>ALTER最常见的一直种用途 是 <strong>增加外键</strong> 定义.</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">ALTER TABLE table_name  ADD [CONSTRAINT [symbol]]</span><br><span class="line">FOREIGN KEY [index_name] (index_col_name,...) REFERENCES other_table(column_name,....)</span><br><span class="line"># []中的内容只作为参考选项，可有可无(计算机书籍里的通用规定)</span><br></pre></td></tr></table></figure>

<p>精简一下:  <strong>ALTER TABLE</strong> table_name  <strong>ADD</strong> [CONSTRAINT [symbol]]<br><strong>FOREIGN KEY</strong> [index_name] <strong>(index_col_name,…) REFERENCES</strong> <strong>reference_table(column_name,….)</strong>；</p>
<p>复杂的表结构更改一般需要手动删除过程，它涉及以下步骤：<br> 用新的列布局<strong>创建一个新表</strong>；
 使用<strong>INSERT SELECT语句从旧表复制数据到新表</strong>。如果有必要，可使用转换函数和计算字段；<br> 检验包含所需数据的新表；<br> 重命名旧表（如果确定，可以删除它）；<br> 用旧表原来的名字重命名新表；<br> 根据需要，重新创建触发器、存储过程、索引和外键。</p>
<p>小心使用ALTER TABLE 使用ALTER TABLE要极为小心，应该在进行改动前做一个完整的备份（模式和数据的备份）。数据库表的更改不能撤销，如果增加了不需要的列，可能不能删除它们。类似地，如果删除了不应该删除的列，可能会丢失该列中的所有数据。</p>
<h1 id="删除表"><a href="#删除表" class="headerlink" title="删除表"></a>删除表</h1><p><strong>删除表</strong>（删除整个表而不是其内容）非常简单，使用DROP TABLE语句即可： </p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">DROP</span> <span class="keyword">TABLE</span> table_name; <span class="comment">#删除整个表了，当然同时也会删除其中的数据(与TRUNCATE 要注意区分)</span></span><br></pre></td></tr></table></figure>

<p>重命名表:</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">RENAME</span> <span class="keyword">TABLE</span> table_name <span class="keyword">TO</span> new_table_name;</span><br></pre></td></tr></table></figure>

<h1 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h1><p>CREATE TABLE用来创建新表，ALTER TABLE用来更改表列（或其他诸如约束或索引等对象），而DROP TABLE用来完整地删除一个表。这些语句必须小心使用，并且应在做了备份后使用。本章还介绍了数据库引擎、定义主键和外键，以及其他重要的表和列选项。</p>

      
    </div>
	<div><div>

    <br>
    <br>
    <div style="text-align:left;color: #ccc;font-size:14px;">
	---本文结束<i class="fa fa-paw"></i>感谢您的阅读---
	<br>
	作者：Xuren
	<br>
	<span>发布时间:</span>2019年07月23日 - 10:25:07
	<br>
	<span>最后更新:</span>2019年08月14日 - 12:44:16
	<br>
	本文链接：<a href="/2019/07/23/MySQL操作表-table/" title="MySQL操作表-table">http://xuren.tech/2019/07/23/MySQL操作表-table/</a>
    <br>
	<!--<span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://xuren.tech/2019/07/23/MySQL操作表-table/"  aria-label="复制成功！"></i></span>
    -->
	版权声明：本文为博主原创文章，转载请附上博文链接！
	</div>
	
	<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    clipboard.on('success', $(function(){
      $(".fa-clipboard").click(function(){
        swal({   
          title: "",   
          text: '复制成功',   
          html: false,
          timer: 500,   
          showConfirmButton: false
        });
      });
    }));  
    </script>

</div>
</div>

    
    
    
	<!-- 新加代码 -->
	<div>
    
        

    
    </div>

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/MySQL必知必会学习-复习/" rel="tag"><i class="fa fa-tag"></i> MySQL必知必会学习-复习</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/07/22/MySQL--INSERT,UPDATE,DELETE/" rel="next" title="MySQL数据插入——INSERT">
                <i class="fa fa-chevron-left"></i> MySQL数据插入——INSERT
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/07/23/MySQL视图与存储过程/" rel="prev" title="MySQL视图与存储过程">
                MySQL视图与存储过程 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "1",
        "bdMiniList": false,
        "bdPic": ""
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      },
      "slide": {
        "bdImg": "5",
        "bdPos": "left",
        "bdTop": "100"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>
<!--//bdimg.share.baidu.com-->

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80NDQ3MS8yMTAwMw"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/freedom.png" alt="Xuren">
            
              <p class="site-author-name" itemprop="name">Xuren</p>
              <p class="site-description motion-element" itemprop="description">做一条最咸的咸鱼!</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">38</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/xuren11" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:296685262@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#创建和操纵表"><span class="nav-number">1.</span> <span class="nav-text">创建和操纵表</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#创建表"><span class="nav-number">1.1.</span> <span class="nav-text">创建表</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#主键再介绍"><span class="nav-number">1.1.1.</span> <span class="nav-text">主键再介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AUTO-INCREMENT"><span class="nav-number">1.1.2.</span> <span class="nav-text">AUTO_INCREMENT</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#指定列的默认值"><span class="nav-number">1.1.3.</span> <span class="nav-text">指定列的默认值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#引擎类型"><span class="nav-number">1.1.4.</span> <span class="nav-text">引擎类型</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#更新表"><span class="nav-number">1.2.</span> <span class="nav-text">更新表</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#删除表"><span class="nav-number">2.</span> <span class="nav-text">删除表</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#小结"><span class="nav-number">3.</span> <span class="nav-text">小结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Xuren</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">63.2k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>








        
<div class="busuanzi-count">
<!--  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
-->
  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  









  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  


  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
<script type="text/javascript" src="/js/src/clicklove.js"></script>

